import Koa from 'koa'
import views from 'koa-views'
import path from 'path'
import bodyParser from 'koa-bodyparser'
import serve from 'koa-static'
import logger from 'koa-logger'
import convert from 'koa-convert'
import co from 'co'
import render from 'koa-ejs'
import route from './app/routes/index'
import config from './config/config'





const app = new Koa();

// 处理全局错误
app.use(async(ctx, next) => {
        try {
            await next()
            if (ctx.status == 404) {
                await ctx.render('404', {
                    title: 'Aibokalv的Blog'
                })
            }
        } catch (err) {
            ctx.body = err
            ctx.status = err.status || 500
        }
    })
    // 设置Header
app.use(async(ctx, next) => {
    await next()
    await ctx.set('X-Powered-By', 'aibokalv@163.com')
})

// 此处为ejs的koa2写法
render(app, {
    root: path.join(__dirname, './app/views'),
    layout: false,
    viewExt: 'ejs',
    cache: false,
    debug: true
});
app.context.render = co.wrap(app.context.render);


app.use(route.routes());

app.listen(config.PORT, function() {
    console.info(`Demos listening on PORT ${config.PORT}`);
    console.info(`You can debug your app with http://127.0.0.1:${config.PORT}`);
    console.info('');
});


module.exports = app;
